package com.otod.sys.emp.service.impl;


import com.otod.base.exception.AppException;
import com.otod.base.service.BaseService;
import com.otod.commons.entity.Page;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.Digests;
import com.otod.commons.utils.Encodes;
import com.otod.commons.utils.StringUtils;
import com.otod.sys.emp.mapper.EmpDetailMapper;
import com.otod.sys.emp.mapper.EmpMapper;
import com.otod.sys.emp.mapper.EmpOrgRoleMapper;
import com.otod.sys.emp.service.IEmpDetailService;
import com.otod.sys.emp.service.IEmpService;
import com.otod.sys.role.service.IRoleService;
import com.otod.sys.vo.AuapREmpOrgRoleVo;
import com.otod.sys.vo.AuapTEmpDetailVo;
import com.otod.sys.vo.AuapTEmpVo;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工信息管理
 *
 * @author jqiu
 */
@Service
@Transactional(readOnly=true)
public class EmpServiceImpl extends BaseService implements IEmpService {

    @Autowired
    IEmpDetailService empDetailService;
    
    @Autowired
    IRoleService roleService;

    @Autowired
    EmpMapper empMapper;

    @Autowired
    EmpOrgRoleMapper empOrgRoleMapper;
    
    @Autowired
    
    EmpDetailMapper empDetailMapper;
    
    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;


    /**
     * 通过员工ID查询员工信息
     *
     * @param 员工ID
     * @return
     */
    public AuapTEmpVo getById(String id) {
        return empMapper.getById(id);
    }
    
    /**
     * 添加员工信息
     *
     * @param empBusBO
     */
    @Transactional
    public void addEmployeeBus(AuapTEmpVo auapTEmpVo, String empRolesIds,
                               AuapTEmpDetailVo empDetail) throws Exception {
        // 1、 添加员工基本信息
        this.addEmployee(auapTEmpVo, empRolesIds);


        // 2、 添加员工详细信息
//		empBusBO.getAuapTEmpDetail().setEmpId(empBusBO.getAuapTEmp().getUuid());// 保存后才有id
//		this.addEmpDetail(empBusBO.getAuapTEmpDetail());

        // 3、 添加员工机构角色关系
//		for (AuapREmpOrgRoleVo AuapREmpOrgRoleVo : empBusBO.getAuapREmpOrgRole()) {
//			AuapREmpOrgRoleVo.setEmpId(empBusBO.getAuapTEmp().getUuid());// 保存后才有id
////			this.addEmpOrgRole(AuapREmpOrgRoleVo);
//		}
    }


    /**
     * 添加员工基本信息及角色信息
     */
    @Override
    @Transactional
    public void addEmployee(AuapTEmpVo auapTEmpVo, String empRolesIds) throws Exception {
        auapTEmpVo.setUuid(super.getUUID());
        this.passwordEncode(auapTEmpVo);
        empMapper.insert(auapTEmpVo);

        String empId = auapTEmpVo.getUuid();
        AuapREmpOrgRoleVo empRoles = new AuapREmpOrgRoleVo();
        if (StringUtils.isNotEmpty(empRolesIds)) {
            String[] arry = empRolesIds.split(";");
            int length = arry.length;
            empOrgRoleMapper.deleteByEmpId(empId);
            for (int i = 0; i < length; i++) {
                empRoles.setRoleId(arry[i]);
                empRoles.setEmpId(empId);
                this.addEmpRoles(empRoles);
            }
        }

    }

    /**
     * 添加员工详细信息
     *
     * @param auapTEmpDetailVo
     * @throws Exception
     */
    @Transactional
    private void addEmpDetail(AuapTEmpDetailVo auapTEmpDetailVo) throws Exception {
        empDetailService.insert(auapTEmpDetailVo);
    }


    @Override
    @Transactional
    public void editEmployeeBus(AuapTEmpVo auapTEmpVo, String empRolesIds,
                                AuapTEmpDetailVo empDetail) throws Exception {
        //1、 更新员工基本信息
        String empId = auapTEmpVo.getUuid();
        AuapTEmpVo OldAuapTEmpVo = empMapper.getById(empId);
        String pwd = OldAuapTEmpVo.getPwd();
        String asyPwd = OldAuapTEmpVo.getAsyPwd();
        BeanUtils.copyProperties(auapTEmpVo, OldAuapTEmpVo);
        OldAuapTEmpVo.setPwd(pwd);
        OldAuapTEmpVo.setAsyPwd(asyPwd);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uuid", OldAuapTEmpVo.getUuid());
        map.put("empNo", OldAuapTEmpVo.getEmpNo());
        map.put("empName", OldAuapTEmpVo.getEmpName());
        map.put("statusFlag", OldAuapTEmpVo.getStatusFlag());
        empMapper.update(map);

        //2、更新员工详细信息
//		AuapTEmpDetailVo auapTEmpDetailVo = empDetailService.getById(empId);
//		BeanUtils.copyProperties(empBusBO.getAuapTEmpDetail(), auapTEmpDetailVo);
//		empDetailService.update(auapTEmpDetailVo);

        //3、删除员工机构角色关系
        AuapREmpOrgRoleVo empRoles = new AuapREmpOrgRoleVo();
        if (StringUtils.isNotEmpty(empRolesIds)) {
            String[] arry = empRolesIds.split(";");
            int length = arry.length;
            empOrgRoleMapper.deleteByEmpId(empId);
            for (int i = 0; i < length; i++) {
                empRoles.setRoleId(arry[i]);
                empRoles.setEmpId(empId);
                this.addEmpRoles(empRoles);
            }
        }
        //5、 添加员工机构角色关系

    }


    /**
     * 添加员工角色信息
     *
     * @param AuapREmpOrgRoleVo
     * @throws Exception
     */
    @Transactional
    private void addEmpRoles(AuapREmpOrgRoleVo empRoles) throws Exception {
        empRoles.setUuid(super.getUUID());

        empOrgRoleMapper.insert(empRoles);
    }


    /**
     * 密码加密
     * <p/>
     * update by superzoc 2014/05/09 完成该功能
     *
     * @param auapTEmpVo
     */
    private void passwordEncode(AuapTEmpVo auapTEmpVo) throws Exception {
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(auapTEmpVo.getAsyPwd().getBytes(), salt, HASH_INTERATIONS);
        auapTEmpVo.setAsyPwd(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
        auapTEmpVo.setPwd(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
    }


    /**
     * 分页查询员工信息列表
     *
     * @param page  分页信息
     * @param param 参数
     * @return 分页信息和结果数据
     */
    public Page queryForList(Page page, Map<String, Object> param) {
        List<AuapTEmpVo> dataList = empMapper.queryForList(page, param);
        page.setAaData(dataList);
//		
//		//测试
//		for(int i=0;i<42;i++){
//			AuapTEmpVo vo = new AuapTEmpVo();
//			vo.setUuid(super.getUUID());
//			vo.setEmpNo("999"+i);
//			vo.setEmpName("名字"+i);
//			vo.setPwd("pwd");
//			empMapper.insert(vo);
//		}

        return page;
    }

    /**
     * 查询员工信息列表
     *
     * @param param 参数
     * @return 结果数据list
     */
    @Override
    public List<AuapTEmpVo> findAll() {
        return empMapper.queryForList(new HashMap<String, Object>());
    }

    /**
     * 查询员工角色列表
     *
     * @param empId
     * @return 结果数据String;String
     */
    @Override
    public String findByEmpId(String empId) {
        List<AuapREmpOrgRoleVo> list = empOrgRoleMapper.findByEmpId(empId);
        int length = list.size();
        StringBuffer str = new StringBuffer();
        if (length > 0) {
            for (int i = 0; i < length; i++) {
                str.append(";").append(list.get(i).getRoleId());
            }
            return str.toString().substring(1);
        }
        return "";
    }

    @Override
    public AuapTEmpVo findByEmpNo(String empNo) {
        AuapTEmpVo empVo = empMapper.getByEmpNo(empNo);
        return empVo;
    }

	/**
	 * 通过empNo查询角色
	 * @param empNo
	 * @return
	 */
	public List<AuapREmpOrgRoleVo> queryForListEmpNo(String empNo) {
		// TODO Auto-generated method stub
		List<AuapREmpOrgRoleVo> auapREmpOrgRoleVos = empOrgRoleMapper.queryForListGetEmpNo(empNo);
		return auapREmpOrgRoleVos;
	}
	/**
	 * 修改手机号码
	 */
	@Transactional
	public void updateEmpTelphone(String telphone, String empId) {
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("empId", empId);
		map.put("mobile", telphone);
		empDetailMapper.update(map);	
	}
	/**
	 * 添加手机号码
	 * @throws Exception 
	 */
	@Transactional
	public void addEmpTelphone(AuapTEmpDetailVo auapTEmpDetailVo) throws Exception {
		addEmpDetail(auapTEmpDetailVo);
	}

	/**
	 * 修改密码
	 */
	@Transactional
	public void updateEmpPassWord(String empNo, String passWord) {
		//密码加密
		byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(passWord.getBytes(), salt, HASH_INTERATIONS);
     	Map<String, Object> map = new HashMap<String,Object>();
		//上次改密码的时间 就是插入当前时间
		map.put("lastmodDt", DateUtils.getDate());
		//不可密码
		map.put("pwd", Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
		//可逆密码
		map.put("asyPwd", Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
		map.put("updatePassWord", empNo);
		empMapper.update(map);		
	}

	/**
	 * 通过uuid 修改密码
	 */
	@Override
	@Transactional
	public void updateEmpNoPassWord(String uuid, String passWord) {
		//密码加密
		byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(passWord.getBytes(), salt, HASH_INTERATIONS);
     	Map<String, Object> map = new HashMap<String,Object>();
		//上次改密码的时间 就是插入当前时间
		map.put("lastmodDt", DateUtils.getDate());
		//不可密码
		map.put("pwd", Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
		//可逆密码
		map.put("asyPwd", Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
		map.put("uuid", uuid);
		empMapper.update(map);		
		
	}
	
	@Override
	@Transactional
	public void deleteByEmpId(String empId) throws AppException {
		 AuapTEmpVo empVo = this.getById(empId);
		 if("super".equals(empVo.getEmpNo())){
			 throw new AppException("管理员账号不能删除");
		 }
		 List<AuapREmpOrgRoleVo> orgRoles = empOrgRoleMapper.findByEmpId(empId);
		 if(Collections3.isNotEmpty(orgRoles)){
			 for (AuapREmpOrgRoleVo orgRole : orgRoles) {
				if("admin".equals(roleService.getById(orgRole.getRoleId()).getRoleNo())){
					throw new AppException("该用户角色为管理员，不能删除");
				}
			}
		 }
		empOrgRoleMapper.deleteByEmpId(empId);
		empMapper.deleteById(empId);
		
	}

	/**
	 * 通过empId 查询对应的角色名字
	 */
	@Override
	public List<AuapREmpOrgRoleVo> queryForListRoleName(String empId) {
		// TODO Auto-generated method stub
		List<AuapREmpOrgRoleVo>  empOrgRoleList = empOrgRoleMapper.queryForListRoleName(empId);
		return empOrgRoleList;
	}

	@Override
	public List<AuapTEmpVo> queryForList(Map<String, Object> param) {
		return empMapper.queryForList(param);
	}

	@Override
	public AuapTEmpVo getByEmpNoAndStatus(Map<String, Object> param) {
		return empMapper.getByEmpNoAndStatus(param);
	}

	
}
